# -*- coding:UTF-8 -*-

from django.shortcuts import render
from django.http import JsonResponse
from mysite.settings import ssh_base_path,base_file_path
from remote_exec.ssh_exec import *
from remote_exec.file_operate import *
from diy_decorator.auth import *

from configuration_database.configuration_info_class import *
from cmdb.base_database import *
from cmdb.views import pageNum

import time
import base64
import logging
# Create your views here.

@login_required()
def show_editor(request):

    return render(request, 'configuration/editor.html', {})

@login_required()
def show_add_form(request):

    type_info = {
        'categorys' : get_biz_type_info()
    }
    return render(request, 'configuration/config_meta_add.html', type_info)

@login_required()
def show_list_form(request):

    page_num=int(request.GET.get('page_num',pageNum))
    page=int(request.GET.get('page',1))
    startpage=(page-1)*page_num
    endpage=startpage+page_num

    config_meta_dict = list_configuration_meta(startpage, endpage)

    count = config_meta_dict['count']
    config_meta_list = config_meta_dict['config_meta_list']

    page_total = int(count/page_num)
    if (count%page_num) > 0 or page_total == 0:
        page_total += 1

    context = {
        'page_total' : page_total,
        'page_list' : range(1,page_total+1),
        'page' : page,
        'page_num' : page_num,
        'count' : count,
        'config_meta_list' : config_meta_list
    }
    return render(request, 'configuration/config_meta_list.html', context)

def del_config_meta(request):
    try:
        config_meta_id = request.POST.get('id')
        delete_cfg_meta(config_meta_id)

        context = {'status' : 1 , 'message' : '删除成功!'}

    except Exception, e:
        context = {'status' : 0, 'message' : str(e)}
        raise e
    return JsonResponse(context, safe=False)

@login_required()
def show_config_pusher(request):
    return render(request, "configuration/config_pusher.html", {})

def update_config_meta(request):
    cursor = get_cursor()
    try:
        svn_path = request.POST.get('svn_path')
        manage_path = request.POST.get('manage_path')
        category = request.POST.get('category')
        page = request.POST.get('page')
        id = request.POST.get('id')

        update_configuration_meta(svn_path, manage_path, category, id, cursor)

        context = {'status' : 1, 'message' : '修改成功!', 'page' : page}

    except Exception, e:
        context = {'status' : 0, 'message' : str(e)}

    return JsonResponse(context, safe=False)

@login_required()
def show_edit_form(request):
    config_meta_info_dict = {}
    try:
        config_meta_id = int(request.GET.get('config_meta_id'))
        page = request.GET.get('page')
        config_meta_info, categorys = get_cfg_meta_info(config_meta_id)

        # categorys = get_biz_type_info()

        config_meta_info_dict = {
            'page' : page,
            'config_meta_info' : config_meta_info,
            'categorys' : categorys
        }

    except Exception, e:
        logging.error('show_edit_form: ' + str(e))

    return render(request, "configuration/config_meta_edit.html", config_meta_info_dict)

def add_config_meta(request):

    context = {}
    try:
        cursor = get_cursor()

        svn_path = request.POST.get('svn_path')
        manage_path = request.POST.get('manage_path')
        category = request.POST.get('category')

        add_configuration_meta_info(svn_path, manage_path, category, cursor)

        context = {
            'status' : 1, 
            'message' : '添加成功!'
        }
    except Exception, e:
        context = {
            'status' : 0, 
            'message' : str(e)
        }
    response = JsonResponse(context, safe=False)
    return response

def get_configure_path(request):

    search = request.POST.get('search','')

    response_dict = {'status':1}
    try:
        result = ''
        error = ''
        if search != '':
            (result,error) = remote_lr_operate(ssh_base_path,search)
        else:
            (result,error) = remote_lr_operate(ssh_base_path)
        if error != '':
            response_dict['status'] = 0
            response_dict['message'] = error
        else:
            response_dict['data'] = result
            
    except Exception,ex:
        print Exception,ex
        response_dict['status'] = 0
        response_dict['message'] = Exception,ex
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

def get_remote_file(request):
    response_dict = {'status':1}
    filename = request.POST.get('filename','')
    
    try:
        pathArr = filename.split('/')
        tmpfilename = pathArr[len(pathArr)-1]
        tmpfilename =  tmpfilename+'.' + str(int(time.time()))
        tmpfilename = base_file_path + tmpfilename
        download_file(filename, tmpfilename)
        context = file_read(tmpfilename)
        file_remove(tmpfilename)
        response_dict['data'] = context
    except Exception,ex:
        response_dict['status'] = 0
        response_dict['message'] = ''
        print Exception,ex
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

def put_remote_file(request):

    response_dict = {'status':1}
    target_file = request.POST.get('filename','')
    content = request.POST.get('content','')
    print content
    try:
        pathArr = target_file.split('/')
        tmpfilename = pathArr[len(pathArr)-1]
        tmpfilename =  tmpfilename+'.' + str(int(time.time()))
        tmpfilename = base_file_path + tmpfilename
        file_write(tmpfilename,content)
        upload_file(tmpfilename, target_file)
        file_remove(tmpfilename)
    except Exception,ex:
        print Exception,ex
        response_dict['status'] = 0
        response_dict['message'] = ''
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

